#!/usr/bin/env python
# -*- coding: utf-8 -*-
# completion -- Objectos de autocompletado del sistema

from PixEntryCompletion import PixEntryCompletion
import gtk
from codificacion import CUTF8
from constantes import MESES
from constantes import SUCURSAL_MATRIZ
import ifd
import wnCuartel, wnTipoControl, wnFicha, wnTipoFicha, wnSector
import wnTipoDocumento, wnInsumo, wnVariedad, wnEstanque
#wnTipoAplicacion /// Decidir si renombrar wnTipoAplicaciones.py -> wnTipoAplicacion


def titulo_campos(campos):
    return [i.replace("_"," ").title() for i in campos]


class GenericCompletion(PixEntryCompletion):

    def __init__(self, entry = gtk.Entry(), sel_func = None,
                    cnx = None, sql = None, modelo=None):

        PixEntryCompletion.__init__(self, entry, selfunc = sel_func,
                                        match_all = False)

        self.cnx = cnx
        self.cursor = self.cnx.cursor()
        self.sql = sql
        if modelo is None:
            self.carga_modelo()
        else:
            self.set_model(modelo)
            self.set_select_column(0)

    def carga_modelo(self):
        self.cursor.execute(self.sql)
        r = self.cursor.fetchall()
        self.titulos = titulo_campos([i[0] for i in self.cursor.description])
        self.modelo.clear()
        if len(r) == 0:
            return
        l = map(ifd.type_to_str, r[0])
        self.modelo = gtk.ListStore(*map(type, l))
        for i in r:
            self.modelo.append(map(CUTF8,i))
        self.set_model(self.modelo)
        self.set_select_column(0)

    def reload(self):
        self.modelo.clear()
        self.cursor.execute(self.sql)
        r = self.cursor.fetchall()
        for i in r:
            self.modelo.append(map(CUTF8,i))

class CompletionCuartel(GenericCompletion):

    def __init__(self, entry = gtk.Entry(), f = None, c = None, tabla=None):
        s = """SELECT c.descripcion_cuartel,
                             c.codigo_cuartel,
                             s.descripcion_sector,
                             v.descripcion_variedad
                      FROM traza.cuartel c
                      INNER JOIN traza.sector s
                      ON c.codigo_sector = s.codigo_sector
                      INNER JOIN traza.variedad v
                      ON v.codigo_variedad = c.codigo_variedad
                      ORDER BY c.descripcion_cuartel""" 
        GenericCompletion.__init__(self, entry, sel_func = f, cnx = c, sql = s)
        self.add_button.connect("clicked", self.on_add_clicked)
        
    def on_add_clicked(self, btn=None):
        dlg = wnCuartel.dlgCuartel(self.cnx, None, False)
        dlg.editando = False
        response = dlg.dlgCuartel.run()
        if response == gtk.RESPONSE_OK:
            self.reload()
            self.select(dlg.entDescripcion.get_text().upper())

            
class CompletionTipoControl(GenericCompletion):

    def __init__(self, entry = gtk.Entry(), f = None, c = None, tabla=None):
        s = """SELECT t.descripcion_tipo_control,
                      u.descripcion_unidad,
                      t.codigo_tipo_control,
                      u.codigo_unidad,
                      t.tipo_resultado
                      FROM traza.tipo_control t
                      INNER JOIN traza.unidad u
                      ON t.codigo_unidad = u.codigo_unidad
                      ORDER BY t.descripcion_tipo_control""" 
        GenericCompletion.__init__(self, entry, sel_func = f, cnx = c, sql = s)        
        self.add_button.connect("clicked", self.on_add_clicked)
        self.add_button.connect("clicked", self.on_add_clicked)
        
    def on_add_clicked(self, btn=None):
        dlg = wnTipoControl.dlgTipoControl(self.cnx, None, False)
        dlg.editando = False
        response = dlg.dlgTipoControl.run()
        if response == gtk.RESPONSE_OK:
            self.reload()
            self.select(dlg.entDescripcion.get_text().upper())

        
    def on_add_clicked(self, btn=None):
        dlg = wnTipoControl.dlgTipoControl(self.cnx, None, False)
        dlg.editando = False
        response = dlg.dlgTipoControl.run()
        if response == gtk.RESPONSE_OK:
            self.reload()
            self.select(dlg.entDescripcion.get_text().upper())

        
class CompletionCodigoDescripcion(GenericCompletion):

    def __init__(self, entry = gtk.Entry(), f = None, c = None, tabla=None):
        s = """SELECT
                        descripcion_%s,
                        codigo_%s
                FROM
                        traza.%s
                ORDER BY
                        descripcion_%s""" % (4*(tabla,))
        GenericCompletion.__init__(self, entry, sel_func = f, cnx = c, sql = s)

class CompletionFicha(GenericCompletion):

    def __init__(self, entry = gtk.Entry(), f = None, c = None, tipo_ficha=None):
        s = """SELECT
                        descripcion_ficha,
                        rut_ficha
                FROM
                        traza.ficha
                WHERE
                        codigo_tipo_ficha = %s
                ORDER BY
                        descripcion_ficha""" % (tipo_ficha)
        GenericCompletion.__init__(self, entry, sel_func = f, cnx = c, sql = s)
        self.add_button.connect("clicked", self.on_add_clicked)
        
    def on_add_clicked(self, btn=None):
        dlg = wnFicha.dlgFicha(self.cnx, None, False)
        dlg.editando = False
        response = dlg.dlgFicha.run()
        if response == gtk.RESPONSE_OK:
            self.reload()
            self.select(dlg.entDescripcion.get_text().upper())


class CompletionPropietario(CompletionFicha):

    def __init__(self, entry = gtk.Entry(), f = None, c = None):
        CompletionFicha.__init__(self, entry, f, c, 1)
        
class CompletionProveedor(CompletionFicha):

    def __init__(self, entry = gtk.Entry(), f = None, c = None):
        CompletionFicha.__init__(self, entry, f, c, 3)        
        
class CompletionEmpleado(CompletionFicha):
    def __init__(self, entry = gtk.Entry(), f = None, c = None):
        CompletionFicha.__init__(self, entry, f, c, 4)  

class CompletionCliente(CompletionFicha):
    def __init__(self, entry = gtk.Entry(), f = None, c = None):
        CompletionFicha.__init__(self, entry, f, c, 2)

class CompletionTransporte(CompletionFicha):
    def __init__(self, entry = gtk.Entry(), f = None, c = None):
        CompletionFicha.__init__(self, entry, f, c, 5)
        
class CompletionTipoFicha(CompletionCodigoDescripcion):

    def __init__(self, entry = gtk.Entry(), f = None, c = None):
        CompletionCodigoDescripcion.__init__(self, entry, f, c, tabla='tipo_ficha')
        self.add_button.connect("clicked", self.on_add_clicked)
        
    def on_add_clicked(self, btn=None):
        dlg = wnTipoFicha.dlgTipoFicha(self.cnx, None, False)
        dlg.editando = False
        response = dlg.dlgTipoFicha.run()
        if response == gtk.RESPONSE_OK:
            self.reload()
            self.select(dlg.entDescripcion.get_text().upper())


class CompletionSector(CompletionCodigoDescripcion):

    def __init__(self, entry = gtk.Entry(), f = None, c = None):
        CompletionCodigoDescripcion.__init__(self, entry, f, c, tabla='sector')        
        self.add_button.connect("clicked", self.on_add_clicked)
        
    def on_add_clicked(self, btn=None):
        dlg = wnSector.dlgSector(self.cnx, None, False)
        dlg.editando = False
        response = dlg.dlgSector.run()
        if response == gtk.RESPONSE_OK:
            self.reload()
            self.select(dlg.entDescripcion.get_text().upper())


class CompletionTipoDocumento(GenericCompletion):

    def __init__(self, entry = gtk.Entry(), f = None, c = None, e = None):
        s = """SELECT
                        descripcion_tipo_documento,
                        codigo_tipo_documento
                FROM
                        traza.tipo_documento
                ORDER BY
                        codigo_tipo_documento"""
        GenericCompletion.__init__(self, entry, sel_func = f, cnx = c, sql = s)                        
        self.add_button.connect("clicked", self.on_add_clicked)
        
    def on_add_clicked(self, btn=None):
        dlg = wnTipoDocumento.dlgTipoDocumento(self.cnx, None, False)
        dlg.editando = False
        response = dlg.dlgTipoDocumento.run()
        if response == gtk.RESPONSE_OK:
            self.reload()
            self.select(dlg.entTipoDocumento.get_text().upper())


class CompletionInsumo(CompletionCodigoDescripcion):

    def __init__(self, entry = gtk.Entry(), f = None, c = None):
        CompletionCodigoDescripcion.__init__(self, entry, f, c, tabla='insumo')
        self.add_button.connect("clicked", self.on_add_clicked)
        
    def on_add_clicked(self, btn=None):
        dlg = wnInsumo.dlgInsumo(self.cnx, None, False)
        dlg.editando = False
        response = dlg.dlgInsumo.run()
        if response == gtk.RESPONSE_OK:
            self.reload()
            self.select(dlg.entDescripcion.get_text().upper())
        
        
class CompletionTipoAplicacion(CompletionCodigoDescripcion):

    def __init__(self, entry = gtk.Entry(), f = None, c = None):
        CompletionCodigoDescripcion.__init__(self, entry, f, c, tabla='tipo_aplicacion')        
#        self.add_button.connect("clicked", self.on_add_clicked)
        
#    def on_add_clicked(self, btn=None):
#        dlg = wnTipoAplicacion.dlgTipoAplicacion(self.cnx, None, False)
#        dlg.editando = False
#        response = dlg.dlgTipoAplicacion.run()
#        if response == gtk.RESPONSE_OK:
#            self.reload()
#            self.select(dlg.entDescripcion.get_text().upper())


class CompletionVariedad(CompletionCodigoDescripcion):

    def __init__(self, entry = gtk.Entry(), f = None, c = None):
        CompletionCodigoDescripcion.__init__(self, entry, f, c, tabla='variedad')
        self.add_button.connect("clicked", self.on_add_clicked)
        
    def on_add_clicked(self, btn=None):
        dlg = wnVariedad.dlgVariedad(self.cnx, None, False)
        dlg.editando = False
        response = dlg.dlgVariedad.run()
        if response == gtk.RESPONSE_OK:
            self.reload()
            self.select(dlg.entDescripcion.get_text().upper())


class CompletionEstanque(CompletionCodigoDescripcion):

    def __init__(self, entry = gtk.Entry(), f = None, c = None):
        CompletionCodigoDescripcion.__init__(self, entry, f, c, tabla='estanque')
        self.add_button.connect("clicked", self.on_add_clicked)
        
    def on_add_clicked(self, btn=None):
        dlg = wnEstanque.dlgEstanque(self.cnx, None, False)
        dlg.editando = False
        response = dlg.dlgEstanque.run()
        if response == gtk.RESPONSE_OK:
            self.reload()
            self.select(dlg.entDescripcion.get_text().upper())

        
class CompletionUnidad(CompletionCodigoDescripcion):

    def __init__(self, entry = gtk.Entry(), f = None, c = None):
        CompletionCodigoDescripcion.__init__(self, entry, f, c, tabla='unidad')

class CompletionProducto(CompletionCodigoDescripcion):

    def __init__(self, entry = gtk.Entry(), f = None, c = None):
        CompletionCodigoDescripcion.__init__(self, entry, f, c, tabla='producto')

class CompletionTemporada(GenericCompletion):

    def __init__(self, entry = gtk.Entry(), f = None, c = None, e = None):
        s = """SELECT 'Temporada ' || date_part('year', fecha_inicio) || '-' 
                    || date_part('year', fecha_termino) as descripcion_temporada,
                    codigo_temporada 
         FROM traza.temporada WHERE abierta = TRUE ORDER BY codigo_temporada"""
        GenericCompletion.__init__(self, entry, sel_func = f, cnx = c, sql = s)

if __name__ == "__main__":
    w = gtk.Window()
    e = gtk.Entry()
    cnx = connect("dbname=traza")
    cnx.autocommit()
    p = CompletionTipoFicha(e, None, cnx, 1)    
    w.add(e)
    w.show_all()
     
    gtk.main()
    

